{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4ab4fe12",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bdasr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "92e5f2f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'NwHRb5zfBdj8ZbpyA20XMwSt'\n",
    "SECRET_KEY = 'h6DevlRFBAeKVwGEV3mxAqjvFFOlWesK'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "29f74a5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "cai_token = fetch_token(API_KEY,SECRET_KEY)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d6679dfb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.5ac8b7b4f238f332e1992c7ab7b0f4ff.2592000.1655887069.282335-25239833'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cai_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "76814273",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "with open(\"1.wav\",\"wb\") as f:\n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "b6c037d6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'怎么没人看呢？'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = eval(asr(token = cai_token,AUDIO_FILE='1.wav'))['result'][0]\n",
    "result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82220f5d",
   "metadata": {},
   "source": [
    "# 图灵机器人："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "87fc6a2c",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# 封装函数\n",
    "import requests\n",
    "TL_key = 'd5d5bb66f66d4da8bedb378df7adfa70'\n",
    "def TuLing(TL_key,text):   \n",
    "    TL_url = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "    payload={\n",
    "        \"reqType\":0,\n",
    "        \"perception\": {\n",
    "            \"inputText\": {\n",
    "                \"text\": text\n",
    "            },\n",
    "        },\n",
    "        \"userInfo\": {\n",
    "            \"apiKey\": TL_key,\n",
    "            \"userId\": \"1234\"\n",
    "        }\n",
    "    }\n",
    "\n",
    "    res = requests.post(TL_url,data=json.dumps(payload)) \n",
    "    return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "68f6351d",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "%E4%BD%A0%E5%88%9A%E5%88%9A%E9%97%AE%E8%BF%87%E4%BA%86%E8%BF%99%E4%B8%AA%E9%97%AE%E9%A2%98%E4%BA%86\n",
      "test on Web Browserhttp://tsn.baidu.com/text2audio?tok=24.1653e9ce57c6bffe3324bac090c69aad.2592000.1655891556.282335-25239833&tex=%25E4%25BD%25A0%25E5%2588%259A%25E5%2588%259A%25E9%2597%25AE%25E8%25BF%2587%25E4%25BA%2586%25E8%25BF%2599%25E4%25B8%25AA%25E9%2597%25AE%25E9%25A2%2598%25E4%25BA%2586&per=4&spd=5&pit=5&vol=5&aue=6&cuid=123456PYTHON&lan=zh&ctp=1\n",
      "result saved as :result.wav\n"
     ]
    }
   ],
   "source": [
    "#1 准备语音文件 并保存 \n",
    "import speech_recognition\n",
    "import pyaudio\n",
    "from pydub import AudioSegment\n",
    "from pydub.playback import play\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "with open(\"1.wav\",\"wb\") as f:\n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "#2  调用百度\n",
    "# API_KEY = 'NwHRb5zfBdj8ZbpyA20XMwSt'\n",
    "# SECRET_KEY = 'h6DevlRFBAeKVwGEV3mxAqjvFFOlWesK'\n",
    "cai_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_result=eval(asr(token = cai_token,AUDIO_FILE='1.wav'))['result'][0]\n",
    "TL_key ='d5d5bb66f66d4da8bedb378df7adfa70'\n",
    "#3  \n",
    "TuLing(TL_key,asr_result[0])\n",
    "#4\n",
    "tts(cai_token,TuLing(TL_key,asr_result[0])\n",
    ")\n",
    " \n",
    "song = AudioSegment.from_wav('result.wav')\n",
    "\n",
    "play (song)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "5981590b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "# API_KEY = '4E1BG9lTnlSeIf1NQFlrSq6h'\n",
    "# SECRET_KEY = '544ca4657ba8002e3dea3ac2f5fdd241'\n",
    "\n",
    "TEXT = \"欢迎使用百度语音合成。\"\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 4\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 5\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 5\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 5\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 6\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "TL_key ='d5d5bb66f66d4da8bedb378df7adfa70'\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "def tts(token,text):\n",
    "\n",
    "    tex = quote_plus(text)  # 此处TEXT需要两次urlencode\n",
    "    print(tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc459bc4",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
